var $tbody = $("#sample-table-1 tbody"),
    allData,
    sortData,
    typeUrl,
    recommendUrl,
    rowData,
    $table,
    selectionIds = [],
    $addTable,
    addSelectionIds = [];
if(sessionStorage.getItem('musicTypes') == '2aeded1129784decbab8b8bf18329c7c'){
    typeUrl = '/community/musicrecommend/findLibraryRecommendMusic';
    recommendUrl = '/community/music/findMusicFromLibrary'
}else{
    typeUrl = '/community/musicrecommend/findRecommendMusic';
    recommendUrl = '/community/musictype/findTypeMusic'
}
/**
 * 日期控件实例化
 */
console.log('16666')
jQuery(function ($) {
    $('.date-picker').datepicker({autoclose: true}).next().on(ace.click_event, function () {
        $(this).prev().focus();
    });
});

// 初始化table
$table = $("#recommend_table").bootstrapTable({
    'url': '/community/musicrecommend/findRecommendMusic',
    'cache':false,
    //'method': 'post',
    'queryParams':function(params){
        params["typeId"] = sessionStorage.getItem('musicTypes');
        params['limit'] = params.limit;
        params['offset'] = params.offset/params.limit + 1;
        sortData = params;
    	return params;
    },
    'toolbar': $('div[data-name="btnCtl"]'),
    'striped': true,
    'pagination': true,
    'sidePagination': 'server',
    'pageSize': globalPageSize,
    'pageList': [],
    'clickToSelect': true,
    'singleSelect': false,
    'smartDisplay': true,
    'responseHandler': function(resb) {
        allData = resb.data.total;
        rowData = resb.data.rows;
        $.each(resb.data.rows, function (i, row) {
            row.checkStatus = $.inArray(row.recommendMusicTypeId, selectionIds) != -1;  //判断当前行的数据id是否存在与选中的数组，存在则将多选框状态变为true
        });
    	return {
    		'total': resb.data.total,
    		'rows': resb.data.rows
    	}
    },
    'onCheckAll': function(){
        $("#deleteMusic").removeAttr("disabled");
    },
    'onUncheckAll': function(){
        $("#deleteMusic").attr("disabled", 'true');
    },
    'onCheck': function() {
        $("#deleteMusic").removeAttr("disabled");
    },
    'onUncheck': function() {
        $("#deleteMusic").attr("disabled", 'true');
    },
    'columns': [{
        'field': 'checkStatus',
        'checkbox': true,
        'valign': 'middle'
        //'class': 'hide'
    },  {
        'field': 'recommendMusicTypeId',
        'title': 'id',
        'class': 'hide musicId'
    },{
        'field': '',
        'title': '推荐排序',
        'align': 'center',
        'valign': 'middle',
        'formatter':function (value,row,index) {
            index+=1;
            return index+(sortData['offset']-1)*sortData['limit'];
        }
    }, {
        'field': 'musicName',
        'title': '音乐名',
        'valign': 'middle',
        'align': 'center'
    }, {
        'field': 'singer',
        'title': '歌手名',
        'valign': 'middle',
        'align': 'center'
    }, {
        'field': 'playCount',
        'title': '使用次数',
        'valign': 'middle',
        'align': 'center'
    }, {
        'field': '',
        'title': '操作',
        'align': 'center',
        'valign': 'middle',
        'formatter': function (value,row,index) {
            if(row.sort == 1){
                var box = "<button class='btn btn-sm btn-success glyphicon glyphicon-arrow-up upType' data-ind='" +index+ "' style='margin-right: 10px' disabled></button><button class='btn btn-sm btn-success glyphicon glyphicon-arrow-down downType' data-ind='" +index+ "' style='margin-right: 10px'></button><button class='btn btn-sm btn-success top'>置顶</button>";
                return box;
            }else if(row.sort == allData){
                var box = "<button class='btn btn-sm btn-success glyphicon glyphicon-arrow-up upType' data-ind='" +index+ "' style='margin-right: 10px'></button><button class='btn btn-sm btn-success glyphicon glyphicon-arrow-down downType' data-ind='" +index+ "' disabled style='margin-right: 10px'></button><button class='btn btn-sm btn-success top'>置顶</button>";
                return box;
            }else{
                var box = "<button class='btn btn-sm btn-success glyphicon glyphicon-arrow-up upType' data-ind='" +index+ "' style='margin-right: 10px'></button><button class='btn btn-sm btn-success glyphicon glyphicon-arrow-down downType' data-ind='" +index+ "' style='margin-right: 10px'></button><button class='btn btn-sm btn-success top'>置顶</button>";
                return box;
            }
        }
    }]
});

//选中事件操作数组
var union = function(array,ids){
    $.each(ids, function (i, id) {
        if($.inArray(id,array)==-1){
            array[array.length] = id;
        }
    });
    return array;
};
//取消选中事件操作数组
var difference = function(array,ids){
    $.each(ids, function (i, id) {
        var index = $.inArray(id,array);
        if(index!=-1){
            array.splice(index, 1);
        }
    });
    return array;
};
var _ = {"union":union,"difference":difference};
//绑定选中事件、取消事件、全部选中、全部取消
$table.on('check.bs.table check-all.bs.table uncheck.bs.table uncheck-all.bs.table', function (e, rows) {
    var ids = $.map(!$.isArray(rows) ? [rows] : rows, function (row) {
        return row.recommendMusicTypeId;
    });
    func = $.inArray(e.type, ['check', 'check-all']) > -1 ? 'union' : 'difference';
    selectionIds = _[func](selectionIds, ids);
});


/**
 * 调整推荐歌曲顺序
 */
$('.row').on('click','.upType,.downType',function(){
    var ind = $(this).data('ind'),
        tableData = $('#recommend_table').bootstrapTable('getSelections')[0],
        url;
    if($(this).attr('class').indexOf('upType')>-1){
        url = '/community/musicrecommend/exchangeSortTop'
    }else{
        url = '/community/musicrecommend/exchangeSortBehind'
    }
    $.ajax({
        url: url,
        type: 'POST',
        dataType: 'json',
        data: {
            'musicrecommendId': tableData.recommendMusicTypeId
        },
        success: function (resp) {
            // alert(resp.message);
            $('#recommend_table').bootstrapTable('refresh')
        },
        error: function (xhr,textStatus,errorThrown) {
            alert(textStatus)
        }
    })
    return false
});

//置顶
$("#recommend_table").on('click', '.top', function () {
    var musicrecommendId = $(this).parent().siblings('.musicId').html();
    $.ajaxSetup({cache:false});
    $.ajax({
        type: "GET",
        url: "/community/musicrecommend/top?musicrecommendId=" + musicrecommendId,
        dataType: 'json',
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", sessionStorage.token);
        },
        success: function (resb) {
            if(resb.success) {
                $("#recommend_table").bootstrapTable("refresh");
            }else{
                alert(resb.message);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
});


/**
 * 音乐模态框展示
 */
$('#musicModal').on('show.bs.modal',function () {
    var sorts;
    $addTable = $('#music_table').bootstrapTable({
        'url': '/community/musictype/findTypeMusic',
        'cache':false,
        //'method': 'post',
        'queryParams':function(params){
            params["typeId"] = sessionStorage.getItem('musicTypes');
            params['limit'] = params.limit;
            params['offset'] = params.offset/params.limit + 1;
            sorts = params;
            return params;
        },
        'toolbar': $('div[data-name="btnCtl"]'),
        'striped': true,
        'pagination': true,
        'sidePagination': 'server',
        'pageSize': globalPageSize,
        'pageList': [],
        'clickToSelect': true,
        'singleSelect': false,
        'smartDisplay': true,
        'responseHandler': function(resb) {
            $.each(resb.data.rows, function (i, row) {
                row.checkStatus = $.inArray(row.musicTypeRelId, addSelectionIds) != -1;  //判断当前行的数据id是否存在与选中的数组，存在则将多选框状态变为true
            });
            return {
                'total': resb.data.total,
                'rows': resb.data.rows
            }
        },
        'onCheck': function() {
            $("button[data-target='#updateModal'], button[data-target='#deleteModal']").removeAttr("disabled");
        },
        'onUncheck': function() {
            $("button[data-target='#updateModal'], button[data-target='#deleteModal']").attr("disabled", 'true');
        },
        'columns': [{
            'field': 'checkStatus',
            'checkbox': true
            //'class': 'hide'
        }, {
            'field': '',
            'title': '推荐排序',
            'align': 'center',
            'formatter':function (value,row,index) {
                index+=1;
                return index+(sorts['offset']-1)*sorts['limit'];
            }
        }, {
            'field': 'musicName',
            'title': '音乐名',
            'align': 'center'
        }, {
            'field': 'singer',
            'title': '歌手名',
            'align': 'center'
        }, {
            'field': 'playCount',
            'title': '使用次数',
            'align': 'center'
        }]
    })
});
$('#music_table').on('check.bs.table check-all.bs.table uncheck.bs.table uncheck-all.bs.table', function (e, rows) {
    var ids = $.map(!$.isArray(rows) ? [rows] : rows, function (row) {
        return row.musicTypeRelId;
    });
    func = $.inArray(e.type, ['check', 'check-all']) > -1 ? 'union' : 'difference';
    addSelectionIds = _[func](addSelectionIds, ids);
});
/**
 * 音乐模态框隐藏
 */
$('#musicModal').on('hidden.bs.modal',function(){
    $('#music_table').bootstrapTable('destroy')
});

/**
 * 添加用户表单验证
 */
$('#addForm').validationEngine('attach', {
    promptPosition: 'centerRight',
    scroll: false,
    binded: true
});

/**
 * 搜索表单提交
 */
$('#dataSearch').click(function () {
    return searchMusic($('#songName').val())
});

/**
 * 添加推荐音乐搜索
 */
function searchMusic(name) {
    if($('#songName').val() == ''){
        $('#music_table').bootstrapTable('refreshOptions',{pageNumber: 1, pageSize: globalPageSize})
    }else{
        $.ajax({
            url: '/community/musictype/findTypeMusicByName',
            type: 'POST',
            dataType: 'json',
            data: {
                'name':name,
                'typeId':sessionStorage.getItem('musicTypes'),
                'offset':0,
                'limit':15
            },
            success:function (resp) {
                // alert(resp.message);
                $('#music_table').bootstrapTable('load',{
                    total:resp.data.total,
                    rows:resp.data.rows
                })
            },
            error:function (xhr,textStatus,errorThrown) {
                alert(textStatus)
            }
        });
    }
}

/**
 * 音乐推荐
 */
$('#recommend').click(function () {
    var tableData = $('#music_table').bootstrapTable('getSelections'),
        data = new Array();
    $.each(tableData,function (index,item) {
        item['typeId'] = sessionStorage.getItem('musicTypes');
        data.push(item)
    });
    $.ajax({
       url:'/community/musicrecommend/addRecommendMusicToTypeBatch',
       type:'POST',
       dataType:'json',
       data:JSON.stringify({"musicTypeRelId": addSelectionIds}),
       contentType:'application/json; charset=UTF-8',
       success:function (resp) {
           alert(resp.message);
       },
       error:function (xhr,textStatus,errorThrown) {
           alert(textStatus)
       },
       complete:function () {
           $('#musicModal').modal('hide');
           $('#musicModal').on('hidden.bs.modal',function () {
               $('#recommend_table').bootstrapTable('refresh')
           })
       }
    })
});

/**
 * 推荐所有音乐
 */
$('#recommendAll').click(function () {
    $.ajax({
        url:'/community/musicrecommend/addAllRecommendMusic',
        type:'POST',
        dataType:'json',
        data:{
            typeId: sessionStorage.getItem('musicTypes')
        },
        //contentType:'application/json; charset=UTF-8',
        success:function (resp) {
            alert(resp.message);
        },
        error:function (xhr,textStatus,errorThrown) {
            alert(textStatus)
        },
        complete:function () {
            $('#musicModal').modal('hide');
            $('#musicModal').on('hidden.bs.modal',function () {
                $('#recommend_table').bootstrapTable('refresh')
            })
        }
    })
});

/**
 * 移除事件触发
 */
$('#deleteMusic').on('click',function () {
    return deleteMusic()
});

/**
 *移除单条推荐歌曲
 */
function deleteMusic() {
    var tableData = $('#recommend_table').bootstrapTable('getSelections'),
        data = new Array();
    $.each(tableData,function (index,item) {
        data.push(item.recommendMusicTypeId)
    });
    var params = {
            "recommendMusicTypeId": selectionIds,
            "typeId": sessionStorage.getItem('musicTypes')
        };
    $.ajax({
        url: '/community/musicrecommend/removeRecommendMusic',
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(params),
        // data: {
        //     "recommendMusicTypeId":data,
        //     "typeId":sessionStorage.getItem('musicTypes')
        // },
        success: function (resp) {
            alert(resp.message);
            $('#recommend_table').bootstrapTable('refresh')
        },
        error: function (xhr,textStatus,errorThrown) {
            alert(textStatus)
        }
    })
}
/**
 *根据session存入的不同参数触发不同的事件
 */
$(function () {
    var val = sessionStorage.getItem('case');
    if(val){
        $("#addModal").modal({show:true});
        $("#addModal").on('show.bs.modal', function() {
            $(this).find("input[type=text]").val("");
        });
    };
    sessionStorage.removeItem('case');
});

/**
 * 添加模态框显示时，清空各输入元素的value
 */
$("#addModal").on('show.bs.modal', function () {
    $(this).find("input[type=text]").val("");
    $(this).find("input[type=password]").val("");
});


// $("#userRecommendType").on('change',function () {
//     $('#stationFormId').submit();
// });

/**
 * 添加头像和头像上传
 */
$(document).ready(function () {
    $("#addPageAddImg").click(function () {
        $('#bord').addClass("borderbox");
        $('#merchantImgs').css({"width": "100%", "height": "100%"});
    });
});

$(function(){
    $('#addPageAddImg').change(function(){
       var formdata = new FormData();
        $.each($('#addPageAddImg')[0].files, function(i,file){
           formdata.append('file',file);
        });
        $.ajax({
           url:'../common/uploadFile',
           type:'POST',
           data: formdata,
           dataType:'json',
           cache: false,
           processData : false,
           contentType : false,
           success:function (resp) {
               var url = resp.data.url;
               if(resp.code == '1'){
                   $('#merchantImgs').attr('src',url)
               }else{
                   alert("预览失败，请重新上传");
               }
           }
        });
    });
});

/**
 * 推荐音乐搜索
 */
$('#songSearch').click(function () {
    return searchRecommendMusic($('#nameSearch').val())
});

function searchRecommendMusic(name){
    if($('#nameSearch').val() == ''){
        $('#recommend_table').bootstrapTable('refreshOptions',{pageSize:1,pageNumber:globalPageSize})
    }else{
        $.ajax({
            url: '/community/musicrecommend/findRecommendMusicByNameAndTypeId',
            type: 'POST',
            dataType: 'json',
            data:{
                name:name,
                typeId:sessionStorage.getItem('musicTypes'),
                offset:0,
                limit:15
            },
            success:function (resp) {
                var data=resp.data;
                $('#recommend_table').bootstrapTable('load',{
                    rows:data.rows,
                    total:data.total
                })
            },
            error:function(xhr,textStatus,errorThrown){
                alert(textStatus)
            }
        })
    }
}
/**
 * 角色操作(新增，更新，删除)
 * @param action [add/update/remove]
 * @param data
 *               [add/update 数据结构 {name: string, description: string, listAuthorityId: array} ]
 *               [delete 数据结构 {roleId: int}]
 * @param async/scync [default async]
 */
function userManagement(action, data, async) {
    var url = null;
    (async === false) ? async = false: async = true;
    if (action === 'add') {
        url = '../user/admin/addUser';
//    } else if (action === 'update') {
//        url = '../user/update';
//    } else {
//        url = '../user/delete';
    };
    return $.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: 'json',
        async: async,
        success: function(resb) {
            alert(resb.message);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
}

